package config

import (
	"ManageServer/defs/dbs"
	"ManageServer/lib"
	"ManageServer/utils/response"
	"ManageServer/utils/validate"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/golang-module/carbon"
	"github.com/jinzhu/gorm"
	"strconv"
)

type Controller struct{}

// 注册路由
func (self Controller) RegisterRoute(r *gin.RouterGroup) {
	r.POST("/config/Create", response.API(self.Create)) // 后台 - 创建配置
	r.POST("/config/Update", response.API(self.Update)) // 后台 - 创建配置
	r.GET("/config/Get", response.API(self.Get))        // 获取信息 - 创建配置
	r.GET("/config/List", response.API(self.List))      // 获取信息 - 配置列表

	//登录类接口不在角色权限内
	lib.SetRouteAuthorization(map[string]map[string][]string{
		"超级管理员": {
			"config": {"Create", "Update", "Get", "List"},
		},
		"管理员": {
			"config": {},
		},
		"患陪": {
			"config": {},
		},
		"职工": {
			"config": {},
		},
	})
}

/**
 * @api {post} /config/Create Create
 * @apiVersion 1.0.0
 * @apiGroup config
 * @apiDescription 创建系统配置
 *
 * @apiParam {String} name 名称
 * @apiParam {String} key 键名称
 * @apiParam {String} [value] 值
 * @apiParam {String} [value_explain] 值备注
 * @apiParam {bool} [hide] 是否显示
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *          "code":"200",
 * 			"msg":"success",
 *			"data":{
 *				"message":200,
 *				"id":2,
 *			}
 *      }
 *
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *			"code":"401",
 * 			"msg":"用户不存在"
 *			"data":{}
 *     }
 */
func (self Controller) Create(c *gin.Context) (data map[string]interface{}, err error) {
	var req dbs.ConfigCreate
	err = c.ShouldBindJSON(&req)
	if err != nil {
		return
	}
	// check validate
	err = validate.Validate(req)
	if err != nil {
		return
	}
	//查看key 是否重复
	var config dbs.DbConfig
	config.Key = req.Key
	if err := config.Exit(); !gorm.IsRecordNotFoundError(err) {
		return data, errors.New("键名称重复")
	}

	interName, exist := c.Get("name")
	if !exist {
		return data, errors.New("__401__获取当前用户失败 ")
	}
	interRole, _ := c.Get("role")

	if interRole.(string) != "超级管理员" {
		return data, errors.New("无此功能权限")
	}
	now := carbon.Now()
	config.Name = req.Name
	config.Value = req.Value
	config.ValueExplain = req.ValueExplain
	config.Hide = req.Hide
	config.CreatedBy = interName.(string)
	config.CreatedAt = now.Time
	config.UpdatedAt = now.Time
	config.FormType = req.FormType

	if err := config.Create(); err != nil {
		return data, errors.New("创建失败,请稍后在尝试")
	}

	data = make(map[string]interface{})
	data["id"] = config.ID

	return data, nil
}

/**
 * @api {post} /config/Update Update
 * @apiVersion 1.0.0
 * @apiGroup config
 * @apiDescription 系统配置修改
 *
 * @apiParam {uint} id 名称
 * @apiParam {String} name 名称
 * @apiParam {String} value 值
 * @apiParam {String} [value_explain] 值备注
 * @apiParam {bool} hide 是否显示
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *          "code":"200",
 * 			"msg":"success",
 *			"data":{
 *			}
 *      }
 *
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *			"code":"401",
 * 			"msg":"用户不存在"
 *			"data":{}
 *     }
 */
func (self Controller) Update(c *gin.Context) (data map[string]interface{}, err error) {
	var req dbs.ConfigUpdate
	err = c.ShouldBindJSON(&req)
	if err != nil {
		return
	}

	// check validate
	err = validate.Validate(req)
	if err != nil {
		return
	}
	//效验是否有着配置
	var config dbs.DbConfig
	config.ID = req.ID
	if err := config.Get(); err != nil {
		return data, errors.New("config update err")
	}
	interName, exist := c.Get("name")
	if !exist {
		return data, errors.New("__401__获取当前用户失败 ")
	}
	now := carbon.Now()
	upData := make(map[string]interface{})
	upData["update_by"] = interName.(string)
	upData["name"] = req.Name
	upData["value"] = req.Value
	upData["value_explain"] = req.ValueExplain
	upData["hide"] = req.Hide
	upData["updated_at"] = now.Time
	upData["form_type"] = req.FormType
	if err := config.Update(upData); err != nil {
		return data, errors.New("config update err")
	}
	return data, nil
}

/**
 * @api {get} /config/Get Get
 * @apiVersion 1.0.0
 * @apiGroup config
 * @apiDescription 系统配置详情
 *
 * @apiParam {uint} [id] 名称
 * @apiParam {String} key 键
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *          "code":"200",
 * 			"msg":"success",
 *			"data":{
 *				"key":"key_name",
 *				"id":2,
 *				"name":"医院名称",
 *				"value":"山西协和医院",
 *				"value_explain":"0 1",
 *				"hide":1,
 *				"created_by":"管理员",
 *				"update_by":"管理员",
 *				"created_at":"2006-01-02 15:04:05",
 *				"update_at":"2006-01-02 15:04:05",
 *			}
 *      }
 *
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *			"code":"401",
 * 			"msg":"用户不存在"
 *			"data":{}
 *     }
 */
func (self Controller) Get(c *gin.Context) (data map[string]interface{}, err error) {
	var id int
	key := c.DefaultQuery("key", "")
	idStr := c.DefaultQuery("id", "0")
	if key == "" && idStr == "0" {
		return data, errors.New("parameter err")
	}

	if idStr != "0" {
		id, _ = strconv.Atoi(idStr)
	}

	//效验是否有着配置
	var config dbs.DbConfig
	config.ID = uint(id)
	config.Key = key
	if err := config.Get(); err != nil {
		return data, errors.New("config 未找到")
	}

	return config.Format(), nil
}

/**
 * @api {get} /config/List List
 * @apiVersion 1.0.0
 * @apiGroup config
 * @apiDescription 系统配置展示列表
 *
 * @apiParam {uint} [id] 名称
 * @apiParam {String} key 键
 * @apiParam {String} [name] 名字
 * @apiParam {bool} [hide] 是否展示
 *
 * @apiSuccessExample {json} Success-Response:
 *     HTTP/1.1 200 OK
 *     {
 *          "code":"200",
 * 			"msg":"success",
 *			"data":{
 *				["key":"key_name",
 *				"id":2,
 *				"name":"医院名称",
 *				"value":"山西协和医院",
 *				"value_explain":"0 1",
 *				"hide":1,
 *				"created_by":"管理员",
 *				"update_by":"管理员",
 *				"created_at":"2006-01-02 15:04:05",
 *				"update_at":"2006-01-02 15:04:05",]
 *			}
 *      }
 *
 * @apiErrorExample {json} Error-Response:
 *     HTTP/1.1 404 Not Found
 *     {
 *			"code":"401",
 * 			"msg":"用户不存在"
 *			"data":{}
 *     }
 */
func (self Controller) List(c *gin.Context) (data map[string]interface{}, err error) {
	var id int
	key := c.DefaultQuery("key", "")
	name := c.DefaultQuery("name", "")
	idStr := c.DefaultQuery("id", "0")
	hideStr := c.DefaultQuery("hide", "")

	if idStr != "0" {
		id, _ = strconv.Atoi(idStr)
	}
	var list dbs.ConfigList
	if hideStr != "" {
		list.Hide, _ = strconv.ParseBool(hideStr)
		list.WhereHide = true
	}
	list.Name = name
	list.ID = id
	list.Key = key

	var config dbs.DbConfig
	configs, err := config.GetList(list)
	if err != nil {
		return data, errors.New("config 未找到")
	}

	var result = make([]map[string]interface{}, 0)
	for _, item := range configs {
		result = append(result, item.Format())
	}
	// 返回
	data = map[string]interface{}{
		"list": result,
	}
	return
}
